import Vue from 'vue'
const planData =  {
  state: {
    planTable: [], //展示的表格数据
    allPlanTable: [],   //所有的表格数据
    compareDefaultTable: null, //比较的表格(提交时)
    columns: [],                //展示的列
    defaultColumns: [],         //所有的列(用于表头筛选)
    copyData: [],                 //存放复制和剪切的数据
    copyFlag: '复制',              //复制的操作类型
    shearId: [],                   //剪切数据的id用于剪切后的粘贴
    filterMap: new Map(),          //筛选条件
    stopPropagation: false,             //不执行全局点击事件的标识位(有些地方不能阻止冒泡，所以使用这个)
    showColOfHeaderConfig: [],          //列配置中的显示的列名
    noShowColOfHeaderConfig: [],        //列配置中的不显示的列名
    allConfig: null,                 //配置
    keyNodeNames: [],                //关键节点名称
    assignments: [],                 // 判断是否删除
    hasSelectData: [],               // 已选中数据
    loadNodeId: null,                   //载入表格下标(用于懒加载)
    userEditable: false,             //当用户是项目经理、项目管理者、项目管理工程师,管理员可操作，否则不行
    resizeInfo: {},                 //记录列宽调整
    keyNodeOpterable: false,             //关键节点操作权限
    columnsFixedNums: 4,              //列表固定数
  },
  getters: {
    getKeyNodeOpterable: state => {
      return state.keyNodeOpterable
    },
    getColumnsFixedNums: state => {
      return state.columnsFixedNums
    },
    getResizeInfo: state => {
      return state.resizeInfo
    },
    getKeyNodeNames: state => {
      return state.keyNodeNames || []
    },
    //可以编辑的列(新增数据时,可编辑的列)
    getEditColumns: state => {
      return ['name', 'targetStartDate', 'targetEndDate', 'resource', 'reviewerReference']
    },
    //所有自定的组件列表
    getSlotColumns: state => (showCols) => {
      return showCols.filter(item => item.slotType);
    },
    //只要本节点或者本节点的父节点的编辑者(editorReference)是本用户，或者userEditable等于true，则可以编辑
    getRowEditable: state => (row,table = null) => {
      let filterTable = table ? table : state.planTable
      const editAble = filterTable.some(ele => (row.parentIds.includes(row.id) || row.id == ele.id) && ele.editorReference == state.allConfig.currentUser)
      return editAble || state.userEditable
    },
    //得到固定列的宽度
    getTableMarginLeft: state => () => {
      let marginLeft = 0
      for(let index = 0; index < state.columnsFixedNums; index++) {
        const col = state.columns[index]
        if (col != undefined) {
          let width = col.style.width.split('px')[0]
          marginLeft += parseInt(width)
        }
      }
      return marginLeft + 'px'
    },
    //展示列
    getPlanColumns: state => (showCols = null) => {
      if (!state.defaultColumns)
        return []
      if (!showCols)
        return state.columns
      state.columns = []
      //根据表头配置设置列头
      showCols.forEach(name => {
        const result = state.defaultColumns.find(target => target.displayName == name)
        if (result != undefined)
          state.columns.push(result)
      })
      state.columns.unshift({
        type: 'selection',
        dataIndex: "selection",
        style: {
          width: '40px',
          minWidth: '40px !important',
        }
      })
      state.columns.push({
        name: 'setting',
        dataIndex: "setting",
        style: {
          width: '60px',
          minWidth: '60px !important',
        },
        slots: {
          title: "customTitle"
        }
      })
      return state.columns
    },
    //默认展示列
    getDefaultPlanColumns: state => {
      return state.defaultColumns 
    },
    //表格数据源
    getPlanTable: state => {
      return state.planTable 
    },
    getCopyData: state => {
      return {
        data: state.copyData,
        flag: state.copyFlag
      }
    },
    //得到所有子节点
    getAllChildNodeByParent: (state) => (target) => {
      const tableSource = state.planTable;
      return tableSource.filter(item => item.parentIds.includes(target.id))
    },
    //判断是否是子节点
    isLastChildNode: (state) => (target,flag = true) => {
      if (flag) {
        return target.activityType != 'WBS'
      } else {
        const tableSource = state.planTable;
        if (tableSource && tableSource.length > 0) {
          return !tableSource.some(item => item.parentIds.includes(target.id))
        }
      }
    },
    //判断是否是新增的节点
    isAddNode: (state) => (id) => {
      return id.toString().indexOf('PIProjectManager.model.Task') != -1
    },
    //得到兄弟节点在表格中的下标
    getLastBrotherNodeIndex: (state) => (parentIds) => {
      let result = 1;
      for (let index = 0, len = state.planTable.length; index < len; index++) {
        if (JSON.stringify(state.planTable[index].parentIds) == JSON.stringify(parentIds))
          result = index;
      }
      return result;
    },
    //得到所有任务
    getAllTable: (state) => () => {
      const compareTable = state.allPlanTable;
      let allTable = JSON.parse(JSON.stringify(state.planTable))
      //因为懒加载，保存时可能没有加载所有数据，在这加上没有加上的数据进行保存(用于linenumber)
      //得到未加载节点的第一个节点下标
      const nodes = JSON.parse(JSON.stringify(compareTable.filter(item => item.parentIds.length == 1)))
      const loadIndex = nodes.findIndex(item => item.id == state.loadNodeId)
      if (loadIndex < nodes.length && loadIndex != -1) {
        const startIndex = compareTable.findIndex(item => item.id == state.loadNodeId)
        allTable.push(...compareTable.slice(startIndex))
      }
      return allTable
    },
    //根据条件得到前置任务时间
    //targetRow前置任务行,millis原数据工期,delay前置任务延期天数
    getDependcyDate: (state) => (targetRow, millis, delay, type) => {
      let targetStart = new Date(targetRow.targetStartDate)
      let targetEnd = new Date(targetRow.targetEndDate)
      switch (type) {
        //开始时间相同
        case 'SS':
          //新的开始日期等于targetRow的开始日期加上延期时间
          targetStart.setDate(targetStart.getDate() + delay)
          targetEnd = new Date(targetStart).setDate(targetStart.getDate() + (millis - 1))
          break;
          //结束时间相同
        case 'FF':
          targetEnd.setDate(targetEnd.getDate() + delay)
          targetStart = new Date(targetEnd).setDate(targetEnd.getDate() - (millis - 1))
          break;
          //currentRow的开始时间时 targetRow结束时间的后一天
        case 'FS':
          targetStart.setDate(targetEnd.getDate() + delay + 1)
          targetEnd = new Date(targetStart).setDate(targetStart.getDate() + (millis - 1))
          break;
          //currentRow的结束时间时 targetRow开始时间的前一天
        case 'SF':
          targetEnd.setDate(targetStart.getDate() + delay - 1)
          targetStart = new Date(targetEnd).setDate(targetEnd.getDate() - (millis - 1))
          break;
      }
      return {
        start: new Date(targetStart),
        end: new Date(targetEnd)
      }
    }
  },
  mutations: {
    setKeyNodeOpterable(state,flag) {
      state.keyNodeOpterable = flag
    },
    setResizeInfo(state, info) {
      return state.resizeInfo = info
    },
    setDefaultColumns(state,columns) {
      state.defaultColumns = columns
    },
    //懒加载数据
    //expandAll：是否展开所有 true 展开所有节点,  false 展开二级节点
    setPlanTable(state, expandAll = null) {
      //得到所有一级节点
      const nodes = JSON.parse(JSON.stringify(state.allPlanTable.filter(item => item.parentIds.length == 1)))
      if (state.loadNodeId == null) {
        state.planTable = [JSON.parse(JSON.stringify(state.allPlanTable[0]))]
        if (nodes.length == 0)
          return
        state.loadNodeId = nodes[0].id
      }
      const loadIndex = nodes.findIndex(item => item.id == state.loadNodeId)
      let tempAddNodes = []
      if (loadIndex != -1) {
        //遍历所有一级节点和一级节点的子节点，当筛选的条数超过50条时，加入planTable
        for (let index = loadIndex, len = nodes.length; index < len; index++) {
          //如果暂存的数据超过目标条数则加入planTable
          let target = nodes[index],tempSave = []
          let childNodes = JSON.parse(JSON.stringify(state.allPlanTable.filter(item => item.parentIds.includes(target.id))));
          let filterNodes = [target, ...childNodes] //筛选的数据
          //遍历父节点和其所有子节点，筛选出符合条件的数据
          for (let filterIndex = 0, lens = filterNodes.length; filterIndex < lens; filterIndex++) {
            let ele = filterNodes[filterIndex]
            ele.show = true;
            let pushFlag = true
            //根据筛选条件找出符合条件的数据
            if (state.filterMap.size > 0) {
              for (let [key, value] of state.filterMap) {
                let selArr = []
                if (value instanceof Array) {
                  value.forEach(data => {
                    selArr.push(...data.split(','))
                  })
                } else {
                  selArr = [...value]
                }
                if (selArr.length == 0)
                  continue;
                //筛选条件
                const selfFlag = key == 'name' ? ele[key].indexOf(value) != -1 : selArr.includes(ele[key]);
                if (ele.activityType == 'WBS') {
                  //当筛选的数据是父节点时，只要有一个子节点符合条件，添加父节点
                  !filterNodes.some(item => item.parentIds.includes(ele.id) &&
                    key == 'name' ? item[key].indexOf(value) != -1 : selArr.includes(item[key])) && (pushFlag = false)
                } else {
                  //筛选子节点
                  !selfFlag && (pushFlag = false)
                }
              }
            }
            //展开收起节点
            if (expandAll != null) {
              if (!expandAll) {
                //只展开二级节点且二级节点是收起的状态
                if (ele.parentIds.length > 1) {
                  ele.show = false;
                } else {
                  ele.isFolder = true;
                }
              } else {
                //展开所有
                ele.isFolder = false;
              }
            }
            //所有筛选条件符合则加入tempSave
            pushFlag && (tempSave.push(ele))
          }
          tempAddNodes.push(...tempSave)
          //显示可查看的数据
          if ((tempAddNodes.filter(item => item.show).length > (state.loadNodeId == null ? 25 : 50) || index == len - 1)) {
            state.planTable.push(...tempAddNodes)
            state.loadNodeId = nodes[index + 1] == undefined ? -1 : nodes[index + 1].id
            break;
          }
        }
      }
    },
    setCopyData(state,{data,flag}) {
      state.copyData = data
      state.copyFlag = flag
    },
    //修改当前行的数据源
    setRowOfPlanTable(state,target) {
      let temp = state.planTable
      const index = temp.findIndex(item => item.id == target.id)
      if (temp && index != -1)
        Vue.set(state.planTable,index,target)
    },
    //修改AllPlanTable的数据源
    setRowOfAllPlanTable(state, target) {
      let temp = state.allPlanTable
      const index = temp.findIndex(item => item.id == target.id)
      if (temp && index != -1)
        Vue.set(state.allPlanTable, index, target)
    },
    //删除alltable的数据源
    delAllTable(state, { index, num }) {
      state.allPlanTable.splice(index, num)
    },
    //将所有表格的数据复制给默认的对比表格
    copyTableForCompare(state) {
      state.compareDefaultTable = JSON.parse(JSON.stringify(state.allPlanTable))
    }
  },
  actions: {
    //新增平行节点
    addNodeOfPlanTable({ state }, {
      target,
      targetIndex
    }) {
      if (state.keyNodeNames.includes(target.name))
        target.KeyNode = '是'
      else
        target.KeyNode = ''
      if (!Array.isArray(target)) {
        state.planTable.splice(targetIndex, 0, target)
      } else {
        state.planTable.splice(targetIndex, 0, ...target)
      }
    }
  }
}
export default planData